package com.joelbitar.switchctrl;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.*;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class ServerDbAdapter {
	private static final String DATABASE_NAME = "switchctrl.db";
	private static final String DATABASE_TABLE = "servers";
	private static final int DATABASE_VERSION = 1;
	
	// The index key
	public static final String KEY_ID = "_id";
	public static final int ID_COLUMN = 0;
	
	// Names of columns
	public static final String KEY_NAME = "name";
	public static final int NAME_COLUMN = 1;
	
	public static final String KEY_URL = "url";
	public static final int URL_COLUMN = 2;
	
	public static final String KEY_USERNAME = "username";
	public static final int USERNAME_COLUMN = 3;
	
	public static final String KEY_PASSWORD = "password";
	public static final int PASSWORD_COLUMN = 4;
	
	public static final String KEY_SHOW = "show";
	public static final int SHOW_COLUMN = 5;
	
	public static final String[] ALL_KEYS = {KEY_NAME, KEY_URL, KEY_USERNAME, KEY_PASSWORD, KEY_SHOW};
	
	private static final String DATABASE_CREATE = "create table " + 
		DATABASE_TABLE + 
		" (" + KEY_ID + " integer primary key autoincrement, " + 
		KEY_NAME + 		" text not null, " + 
		KEY_URL + 		" text not null, " +
		KEY_USERNAME + 	" text not null, " +
		KEY_PASSWORD + 	" text not null, " +
		KEY_SHOW + 		" boolean);";
	
	private ServerDbHelper dbHelper;
	
	private SQLiteDatabase db;

	private final Context context;
	
	public ServerDbAdapter(Context context) {
		this.context = context;
		this.dbHelper = new ServerDbHelper(context, ServerDbAdapter.DATABASE_NAME, null, ServerDbAdapter.DATABASE_VERSION);
		
		// Trying to get a writable database, if not, get a readable database.
		try {
			db = dbHelper.getWritableDatabase();
		} 
		catch (SQLiteException e) {
			db = dbHelper.getReadableDatabase();
		}
	}
	
	public void close() {
		db.close();
	}
	
	private ContentValues getContentValuesFromServer(Server server) {

		ContentValues contentValues = new ContentValues();
		// TODO Insert real content values
		contentValues.put(KEY_NAME, server.getName());
		contentValues.put(KEY_URL, server.getHosturl());
		contentValues.put(KEY_USERNAME, server.getUsername());
		contentValues.put(KEY_PASSWORD, server.getPassword());
		contentValues.put(KEY_SHOW, server.getVisible());
		
		Log.w("contentvalues", "Getting Content Values");
		
		Log.i("name", server.getName());
		Log.i("url", server.getHosturl());
		Log.i("username", server.getUsername());
		Log.i("password", server.getPassword());
		Log.i("show", "show:" + server.getVisible());
		
		return contentValues;
	}
	
	public long insertServer(Server server) {
		
		ContentValues contentValues = getContentValuesFromServer(server);
		
		return db.insert(DATABASE_TABLE, null, contentValues);
	}
	
	// TODO remove entry
	
	
	public Cursor getAllServers() {
		return db.query(DATABASE_TABLE, new String[] {
				KEY_ID,
				KEY_NAME,
				KEY_URL,
				KEY_USERNAME,
				KEY_PASSWORD,
				KEY_SHOW
				}, null, null, null, null, null);
	}
	
	public Server getServer(long index) {
		
		Log.i("gettingserver", "Getting server");
		Log.i("id", "" + index);
		
		Server result = new Server();
		

		Log.i("gettingserver", "blah");
		
		Cursor cursor = db.query(DATABASE_TABLE, new String[] {
				KEY_ID,
				KEY_NAME,
				KEY_URL,
				KEY_USERNAME,
				KEY_PASSWORD,
				KEY_SHOW
				}, KEY_ID + " = " + index, null, null, null, null);

		Log.i("cursorcount", "" + cursor.getCount());
		
		if((cursor.getCount() == 0) || !cursor.moveToFirst()){
			throw new SQLException ("No server found with ID: " + index);
		}
		
		result.setFromCursor(cursor);
		
		return result;
	}
	
	public int updateServer(Server server) {
		String where = KEY_ID + "=" + server.getId();
		
		Log.i("updateserver", "UPDATE");
		Log.i("updateserver", where);
		
		ContentValues contentValues = getContentValuesFromServer(server);
		
		return db.update(DATABASE_TABLE, contentValues, where, null);
	}
	
	
	
	private static class ServerDbHelper extends SQLiteOpenHelper {
		public ServerDbHelper(Context context, String name, CursorFactory factory, int version) {
			super(context, name, factory, version);
		}
		
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			
			Log.w("ServerAdapter", "UPPGRADING");
			
			// TODO real update shoudl be done
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			
			onCreate(db);
		}
	}

	public void deleteServer(Server server) {
		// TODO Auto-generated method stub
		db.delete(DATABASE_TABLE, KEY_ID + " = " + server.getId(), null);
	}

	public ArrayList<Server> getAllActiveServers() {
		// TODO Auto-generated method stub
		
		ArrayList<Server> servers = new ArrayList<Server>();
		
		Cursor cursor = db.query(DATABASE_TABLE, new String[] {
				KEY_ID,
				KEY_NAME,
				KEY_URL,
				KEY_USERNAME,
				KEY_PASSWORD,
				KEY_SHOW
				}, KEY_SHOW + " = 1", null, null, null, null);
		
		if((cursor.getCount()) == 0 || !cursor.moveToFirst()) {
			
		}else{
			do{
				Server server = new Server();
				
				server.setFromCursor(cursor);
				
				servers.add(server);
			}while(cursor.moveToNext());
		}
		
		return servers;
	}
}
